#include <iostream>
#include <stdio.h>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define N 2
#define NUM 1024

using namespace std;

void writer(int wfd)
{
    string s="hello world";
    pid_t self=getpid();
    int number=0;

    char buffer[NUM];
    while(true)
    {
        //sleep(1);
        // 构建发送字符串
        // buffer[0] = 0; // 字符串清空, 只是为了提醒阅读代码的人，我把这个数组当做字符串了
        // snprintf(buffer,sizeof(buffer),"%s-%d-%d",s.c_str(),self,number++);
        // cout<<buffer<<endl;
        // //发送给父进程
        // write(wfd,buffer,strlen(buffer));//strlen不需要加1那是C语言规则，
        char c='c';
        write(wfd,&c,1);
        number++;
        cout<<number<<endl;
        //if(number>=5) break;
    }
}

void reader(int rfd)
{
    char buffer[NUM];
    while(true)
    {
        buffer[0]=0;
        ssize_t n=read(rfd,buffer,sizeof(buffer));
        if(n>0)
        {
            buffer[n]=0;
            cout<<"father get a message["<<getpid()<<"]#"<<buffer<<endl;
        }
        else if(n==0)
        {
            printf("father read file done\n");
        }
        else break;
    }
}

int main()
{
    int pipefd[N]={0};
    int n =pipe(pipefd);
    if(n<0) return 1;
    //child->w,father->r
    pid_t id=fork();
    if(id<0) return 2;
    if(id==0)
    {
        //child
        close(pipefd[0]);//关闭读端，只写
        //IPC code
        writer(pipefd[1]);
        //进程间通信结束后可手动关闭，系统也会自动关闭
        close(pipefd[1]);
        exit(0);
    }
    //father
    sleep(50);
    reader(pipefd[0]);
    pid_t rid=waitpid(id,nullptr,0);//回收子进程
    if(rid<0) return 3;

    close(pipefd[0]);
    return 0;
}